//
//  ContentViewController.swift
//  BlueToothBackground
//
//  Created by macvivi on 2021/11/8.
//

import UIKit

class ContentViewController: UIViewController {
    
    
    @IBOutlet var connectState: UILabel!
    
    
    @IBOutlet var rssiValueLabel: UILabel!
    
    @IBAction func sendBtnClick(_ sender: Any) {
        
        let data = Data([1,1,1])
        

        XYCentralManager.shared.writeWithoutResponse(peripheral: BTBManager.shared.peripheral, characteristic: BTBManager.shared.characteristic, data: data)
    }
    
    var _timer:Timer!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(disconnect), name: NSNotification.Name(rawValue: "disconnect"), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(connected), name: NSNotification.Name(rawValue: "connect"), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(readRSSI(notice:)), name: NSNotification.Name(rawValue: "rssi"), object: nil)
//
//          _timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { (timer) in
//            if BTBManager.shared.peripheral.state == .connected && XYCentralManager.shared.findedCharacteristic{
//                BTBManager.shared.peripheral.readRSSI()
//            }
//            
//        }

        // Do any additional setup after loading the view.
    }
    
    @objc func disconnect(){
        connectState.text = "连接断开"
    }
    
    @objc func connected(){
        connectState.text = "已连接"
    }
    
    @objc func readRSSI(notice:NSNotification){
         let rssi:NSNumber = notice.userInfo!["rssi"] as! NSNumber
        rssiValueLabel.text = String(rssi.intValue)
        printXY(rssi.intValue, obj: self, line: #line)
        if rssi.intValue > -50 {
            let data = Data([5,5,5])
            
            XYCentralManager.shared.write(peripheral: BTBManager.shared.peripheral, characteristic: BTBManager.shared.characteristic, data: data, errorClosure: nil)
            _timer.invalidate()
        }
//        printXY(rssi.intValue, obj: self, line: #line)
    }
    
    override func viewWillDisappear(_ animated: Bool) {

    }
    
    deinit {
        printXY("deinit", obj: self, line: #line)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
